<?php

include_once('../../index.php');
include_once('templates/core/Smarty.class.php');
$smarty = new smarty();

$isCookied = isset($_COOKIE['identify'], $_COOKIE['hash']);
$isReceiveForm = count($_POST) > 0;
$isIdentify = false;
$message = '';

if ($isCookied) {
  //index properties
  $post = new Post($db);
  $post->identify = $_COOKIE['identify'];
  $post->hash = $_COOKIE['hash'];
  $isIdentify = $post->identify();
}

//Is not identify user
if (!$isIdentify) {
  // return to login
  header('Location: users.php?page=login');
  return;
}

//Is superuser needed
if ($isIdentify) {
  //SUPERUSER PROCESS
  $isSuperUser = $post->is_super_user();
}

if (!$isSuperUser) {
  header('Location: /');
  return;
}

if ($isReceiveForm) {

  $isReceiveData =
    isset($_POST['name'],
          $_POST['password']);

  if (!$isReceiveData) {
    $message = 'Ingrese todos los datos';
  }

  if ($isReceiveData) {
    $post = new Post($db);
    $post->identify = $_COOKIE['identify'];
    $post->hash = $_COOKIE['hash'];
    $post->rol = isset($_POST['rol']) ? $_POST['rol'] : 0;
    $post->name = $_POST['name'];
    $post->password = hash ( 'sha512', $_POST['password']);

    //is duplicate user
    if (!$post->is_new_user()) {
      $message = 'Usuario ya existe intente otro nombre de usuario.';
    }

    $message = 'TODO GENIAL';
    $isCreated = $post->create();

    //create user
    if ($isCreated) {
      header('Location: users.php?page=read');
    }

    if (!$isCreated) {
      $message = 'Algo fallo en `$isCreated`';
    }
  }
}

//DECLARE FORM VARIABLES
$smarty->assign('rol', 1);
$smarty->assign('name', '');
$smarty->assign('password', '');
$smarty->assign('message', $message);
$smarty->display("templates/{$_GET['page']}.tpl");

?>